package com.thread.pool.application.controller;

import com.thread.pool.application.scanner.execute.AnnotationScanner;
import com.thread.pool.application.scanner.factory.ActionHandleFactory;
import com.thread.pool.application.scanner.model.ActionEntity;
import com.thread.pool.application.scanner.pool.ThreadPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.concurrent.locks.ReentrantReadWriteLock;

@RestController
public class UserController {
//    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
//            //线程池大小
//            3,
//            //线程池最大数量
//            10,
//            //超出 corePoolSize 后创建的线程存活时间或者是所有线程最大存活时间，取决于配置。
//            10L,
//            //keepAliveTime 的时间单位
//            TimeUnit.SECONDS,
//            //任务队列，是一个阻塞队列，当线程数已达到核心线程数，会将任务存储在阻塞队列中。100-队列数量
//            new LinkedBlockingQueue(100),
//            //线程名称
//            // TODO: 2022/11/6 增加线程工厂
//            new NamedThreadFactory("concurrent-task-pool-"),
//            //拒绝策略；当队列已满并且线程数量达到最大线程数量时，会调用该方法处理该任务。
//            new ThreadPoolExecutor.CallerRunsPolicy());


    @Autowired
    private ThreadPoolConfig threadPoolConfig;

    //@Async("getThreadPoolExecutor")
    @PostMapping("/getUserInfo")
    public void getUserInfo(){
        try {
            Map<String, Object> paramMap = new HashMap<>();
            List<String> policyList = new ArrayList<>();
            policyList.add("MONDAY");
            policyList.add("HELLO");
            policyList.add("TUESDAY");
            paramMap.put("policy", policyList);
            AnnotationScanner annotationScanner = new AnnotationScanner();
            Map<String, ActionEntity> scanner = annotationScanner.scanner();

            paramMap.putAll(scanner);
            ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
            ReentrantReadWriteLock.WriteLock writeLock = readWriteLock.writeLock();
            for (String policy : policyList) {
                Future<Map<String, Object>> resultFuture = threadPoolConfig.getThreadPool().submit(new ActionHandleFactory(paramMap, policy,writeLock));
                System.out.println(resultFuture.get().get("threadName"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
